package connector

import (
	"context"
	"github.com/topfreegames/pitaya/v3/examples/demo/protos"
	"github.com/topfreegames/pitaya/v3/pkg"
	"github.com/topfreegames/pitaya/v3/pkg/component"
	"github.com/topfreegames/pitaya/v3/pkg/logger"
	"github.com/topfreegames/pitaya/v3/pkg/session"
	"server/pb/pb_chat"
	"strconv"
)

// Handler 结构体必须继承一下 Base 类
type Handler struct {
	component.Base
	app pitaya.Pitaya
}

func NewHandler(app pitaya.Pitaya) *Handler {
	return &Handler{
		app: app,
	}
}

func (this *Handler) Init() {
	logger.Log.Info("connector handler 启动成功")
	//this.app.GetSessionFromCtx()
	//// 获取 session 模块
	//sessionModule, err := this.app.GetModule("session")
	//if err != nil {
	//	panic(err)
	//}
	//logger.Log.Info("sessionModule=", sessionModule)

	//err:=this.app.GroupCreate(context.Background(), "online")
	//if err!=nil{
	//	panic(err)
	//}

	session.OnSessionBind(func(ctx context.Context, s session.Session) error {
		logger.Log.Infoln("session 绑定成功")
		s.OnClose(func() {
			onUserOffline(ctx, s)
		})
		onUserOnline(ctx, s)
		return nil
	})
	//session.OnSessionBind(func(ctx context.Context, s session.Session) error {
	//	logger.Log.Infoln("session 绑定成功")
	//	_ = s.OnClose(func() {
	//		onUserOffline(ctx, s)
	//	})
	//	onUserOnline(ctx, s)
	//	return nil
	//})
}

func (this *Handler) Login(ctx context.Context) error {
	_logger := pitaya.GetDefaultLoggerFromCtx(ctx)
	tmpSession := this.app.GetSessionFromCtx(ctx)

	fakeId := tmpSession.ID()
	// 2.绑定session uid
	err := tmpSession.Bind(ctx, strconv.Itoa(int(fakeId))) // binding tmpSession uid
	if err != nil {
		_logger.Error(err)
		return pitaya.Error(err, "RH-000", map[string]string{"failed": "bind"})
	}
	_ = tmpSession.Set("uid", fakeId)

	// 3.更新online数据
	if err := this.app.GroupAddMember(ctx, "online", tmpSession.UID()); err != nil {
		_logger.Error(err)
	}
	//this.Users[tmpSession.UID()] = struct{}{}

	// 5.关闭连接时清除online数据
	err = tmpSession.OnClose(func() {
		logger.Log.Info("connector handler,user disconnect, fakeId= ", fakeId)
		onUserOffline(ctx, tmpSession)
	})
	onUserOnline(ctx, tmpSession)

	return nil
}

// SendRPC sends rpc
func (this *Handler) SendRPC(ctx context.Context, msg *protos.RPCMsg) (*protos.RPCRes, error) {
	ret := &protos.RPCRes{}
	err := this.app.RPC(ctx, "Chat.Remote.JoinPlayerToChatGroup", ret, msg)
	if err != nil {
		return nil, pitaya.Error(err, "RPC-000")
	}
	return ret, nil
}

func onUserOnline(ctx context.Context, s session.Session) {
	//joinPlayerToChatGroup(ctx, s.UID())
	err := pitaya.RPC(ctx, "Chat.Remote.UserStatusChange", &pb_chat.UserChatReply{}, &pb_chat.UserChatStatus{
		UID:    s.UID(),
		Status: 1,
	})
	if err != nil {
		logger.Log.Error(err)
	}
}

func onUserOffline(ctx context.Context, session session.Session) {
	//removePlayerFromChatGroup(ctx, session.UID())
	err := pitaya.RPC(ctx, "Chat.Remote.UserStatusChange", &pb_chat.UserChatReply{}, &pb_chat.UserChatStatus{
		UID:    session.UID(),
		Status: 2,
	})
	if err != nil {
		logger.Log.Error(err)
	}
}

//
//// 离开聊天group
//func removePlayerFromChatGroup(ctx context.Context, uid string) {
//	//打印一下人数
//	membersCount1, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
//	logger.Log.Infof("离开前,[%s group]人数：%d", constants.WoldGroup, len(membersCount1))
//	_ = pitaya.GroupRemoveMember(ctx, constants.WoldGroup, uid)
//	//打印一下人数
//	membersCount2, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
//	logger.Log.Infof("离开后,[%s group]人数：%d", constants.WoldGroup, len(membersCount2))
//}
//
//// 加入聊天group
//func joinPlayerToChatGroup(ctx context.Context, uid string) {
//	membersCount1, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
//	logger.Log.Infof("加入前，group[%s]人数：%d", constants.WoldGroup, len(membersCount1))
//	//加入聊天室
//	if isContain, err := pitaya.GroupContainsMember(ctx, constants.WoldGroup, uid); isContain {
//		logger.Log.Error(err)
//		logger.Log.Infof("加入group错误,[%s group]玩家已存在：%s", constants.WoldGroup, uid)
//	} else {
//		_ = pitaya.GroupAddMember(ctx, constants.WoldGroup, uid)
//		membersCount2, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
//		logger.Log.Infof("加入后，[%s group]人数：%d", constants.WoldGroup, len(membersCount2))
//	}
//}
